<template>
    <div class="function-panel">

        <div v-if="isClassing" class="btn-wrap">
          <div @click="doClassEnd()">下课</div>
        </div>
        
        <!-- 举手菜单 -->
        <div v-if="0" class="btn-wrap">
            <SpeakApplyMenu/>
        </div>

        <!-- 屏幕分享菜单 -->
        <div v-if="!isStudent" class="btn-wrap">
            <ShareScreenMenu/>
        </div>

        <div v-if="isTeacher&&hasPad" class="btn-wrap">
          <div @click="syncAuto()">开始同步</div>
        </div>

        <!-- 弹幕按钮 -->
        <div v-if="0" @click="toggleBarrage()" class="btn-wrap">
            <i v-if="isBarrageOn" class="icon icon-barrage-on"></i>
            <i v-else class="icon icon-barrage-off"></i>
            {{barrageState}}
        </div>

        <!-- 线路切换 -->
        <select class="cdn-node-list" v-if="cdnList.length > 1 && canSwitchCdn" v-model="currentNode" name="cdn" id="cdn-list">
            <option v-for="index in cdnList.length" :key="index" :value="index">{{index | cdnListFilter}}</option>
        </select>

        <div v-if="viewTime&&!isStudent" class="time-wrap">
            <img src="@/assets/room/time-icon.png" /><span>{{lastTip}}时间：{{lastTimeStr}}</span>
        </div>

    </div>
</template>

<script>
import language from '@/language/main'
import SpeakApplyMenu from './SpeakApplyMenu'
import ShareScreenMenu from './ShareScreenMenu'
import {
  formatSeconds
} from '@/utils/tools'

let store = BJY.store
let eventEmitter = BJY.eventEmitter
let auth = BJY.auth

export default {
  components: {
    SpeakApplyMenu,
    ShareScreenMenu
  },
  data () {
    return {
      isTeacher: false,
      hasPad: false,
      lastTip: '课堂剩余',
      lastTimeStr: '',
      viewTime: false,
      status: '',
      language: language,
      isStudent: auth.isStudent(),
      barrage: null,
      isBarrageOn: false,
      cdnList: [],
      currentNode: 1,
      isClassing: false,
      preOutClass: 0,
      canSwitchCdn: !BJY.auth.isWebRTC()
    }
  },
  computed: {
    barrageState () {
      return this.isBarrageOn ? language.BARRAGE_ON : language.BARRAGE_OFF
    }
  },
  watch: {
    currentNode (newIndex, oldIndex) {
      console.log(newIndex)
      eventEmitter.trigger(
        eventEmitter.DOWNLINK_SERVER_NODE_CHANGE_TRIGGER,
        {
          index: newIndex - 1
        }
      )
    }
  },
  filters: {
    cdnListFilter (index) {
      return '线路' + index
    }
  },
  methods: {
    syncAuto () {
      eventEmitter.trigger(eventEmitter.ZWZ_PAD_CMD, {
        cmd: 'PAD:ROOM',
        event: 'SOCKET',
        args: ['sync:cmd', {broadcast: true}]
      })
      this.$Toast('已开始同步请稍侯')
    },
    handleStart () {
      if (store.get('class.started')) {
        eventEmitter.trigger(eventEmitter.CLASS_END_TRIGGER)
      } else {
        eventEmitter.trigger(eventEmitter.CLASS_START_TRIGGER)
      }
    },
     doClassEnd () {
      eventEmitter.trigger(eventEmitter.CLASS_END_TRIGGER)
    },
    toggleBarrage () {
      let isOpen = this.barrage.isOpened()
      if (isOpen) {
        this.barrage.close()
        this.isBarrageOn = false
      } else {
        this.barrage.open()
        this.isBarrageOn = true
      }
    }
  },
  created () {
    this.isTeacher = BJY.auth.isTeacher()
    this.hasPad = BJY.store.get('yxp_has_pad')
    this.preOutClass = Number(BJY.query.pre_out_class) || 0

    if (store.get('class.started')) {
      this.status = language.CLASS_END
    } else {
      this.status = language.CLASS_START
    }

    eventEmitter
      .on(
        eventEmitter.CLASS_START,
        () => {
          this.status = language.CLASS_END
          this.$Toast(language.TIP_CLASS_START)
        }
      )
      .on(
        eventEmitter.CLASS_END,
        () => {
          this.status = language.CLASS_START
          this.$Toast(language.TIP_CLASS_END)
        }
      )
      .on(eventEmitter.CLASS_START, () => {
      this.isTeacher && this.preOutClass == 0 && (this.isClassing = true)
    })
    .on(eventEmitter.CLASS_END, () => {
      this.isTeacher && (this.isClassing = false)
    })
    .on(eventEmitter.ZWZ_SETBTN_CLASSEND, (event, data) => {
      this.isTeacher && (this.isClassing = data.isClassing)
    })
    // 获取k可用的cdn节点
    this.cdnList = BJY.data.server.getLiveServerList()
  },
  mounted () {
    // 调用 create 方法创建弹幕组件
    // 弹幕组件不需要独立的容器，只需要在create中提供挂载的容器
    this.barrage = new BJY.Barrage({
    // 组件父容器
      container: $('.class-panel'),
      // 移动速度，每秒移动多少个像素
      speed: 100,
      // 最长可显示多少个字，超过这个字数的会过滤
      maxLength: 20,
      // 在 top - bottom 的区间出现弹幕
      top: 30,
      bottom: 30,
      // 轨道高度
      trackHeight: 30,
      // 是否只显示文本消息
      textOnly: false,
      // 如果需要自定义弹幕内容，可实现此方法
      renderContent: function (data) {
        return data.content
      }
    })
    // 剩余时间及等时业务处理
    let preOutClass = this.preOutClass
    let lastTimeConf = 1000*60*5
    let timeOps = {}
    let opkey = ''
    let waitConfTime = Number(this.$route.query.wait_time) || 1000*60*5
    let wstore = window.localStorage
    let waitTime = 0
    let lastControll = null
    let $T = new Date().getTime()
    let $TT = 0
    let bclass = store.get('class')
    let edelayTime = +bclass.endDelayTime * 1000
    let diff = (+bclass.endTimeTs + edelayTime) - $T
    let vdiff = 0
    let step = 1000
    let isOverStartTime = $T > bclass.startTimeTs ? true : false
    // diff = 1000*10
    if(diff > 0){
      lastControll = setInterval(() => {
        $TT = new Date().getTime()
        if(!isOverStartTime && $TT > bclass.startTimeTs){
          eventEmitter.trigger(eventEmitter.ZWZ_SETTUB_INIT)
          isOverStartTime = true
        }
        // 等时操作
        opkey = `zwz:wait:${bclass.id}`
        waitTime = Number(wstore.getItem(opkey)) || 0
        if(waitTime > 0 && ($TT - waitTime) > waitConfTime){//离线超时操作
          if(!timeOps[opkey]){
            eventEmitter.trigger(eventEmitter.ZWZ_SETTUB_INIT)
            timeOps[opkey] = 1
          }
        }else{
          if(!!timeOps[opkey]) delete timeOps[opkey]
        }
        // 显示剩余
        vdiff = diff - edelayTime
        if(diff < (lastTimeConf + edelayTime)){
          this.viewTime = true
          if(edelayTime > 0 && diff <= edelayTime){
            vdiff = diff
            this.lastTip = '关闭课堂'
          }
        }
        this.lastTimeStr = formatSeconds(Math.max(0, Math.floor(vdiff/1000)), [' ', ':'])
        // 倒时间结束
        if(diff <= 0){
          if(!this.isStudent){
            eventEmitter.trigger(eventEmitter.CLASS_END_TRIGGER)
          }
          clearInterval(lastControll)
          return false
        }
        // 开始显示下课按钮
        if(preOutClass > 0){
          if($TT > (bclass.endTimeTs - preOutClass*60*1000)){
            eventEmitter.trigger(eventEmitter.ZWZ_SETBTN_CLASSEND, {isClassing: true})
          }
        }
        diff -= step
      }, step)
    }
    if(this.isTeacher && preOutClass == 0){
      this.isClassing = BJY.store.get('class.started')
    }
  },
  beforeDestroy () {}
}
</script>

<style lang='less' scoped>
//@import url(); 引入公共css类
.function-panel {
    display: flex;
    justify-content: space-around;
    align-items: center;

    & > * {
        margin: 0 10px;
        padding: 2px 8px;
        cursor: pointer;
        display: flex;

        &:hover {
            border-radius: 4px;
            background-color: rgba(255, 255, 255, .3);
            color: #fff;
            transition: all .3s;
        }
    }

    .btn-wrap {
        align-items: center;

        .icon-barrage-on, .icon-barrage-off {
            font-size: 22px;
            margin-right: 5px;
        }
    }
    .time-wrap {
      display: flex;
      align-items: center;
      img {
        width: 15px;
        height: 15px;
        margin-right: 4px;
      }
      span {
        color: #FB1F49;
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
      }
    }
}
</style>
